﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.Model;
using Kiiro.SiteDefinition.ControlTemplates;
using Kiiro.SiteDefinition.Core;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace Kiiro.SiteDefinition.ProjectPages
{
    public partial class EditDiscussion : BasePage
    {
        #region Properties
        public Discussion Discussion
        {
            get;
            set;
        }

        public CustomFieldCollection CustomFields
        {
            get { return ( CustomFieldCollection ) v2CustomFieldCollection; }
        }

        public AttachmentControl Attachments
        {
            get { return ( AttachmentControl ) attachmentControl; }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }

        public FormButtons Buttons
        {
            get { return ( FormButtons ) v2FormButtons; }
        }

        public WMDEditor WMDTextEditor
        {
            get { return (WMDEditor)v2WMDEditor; }
        }
        #endregion

        #region Page Events
        protected override void OnInit ( EventArgs e )
        {
            base.OnInit ( e );
            CustomFields.ControlMode = SPControlMode.Edit;
            NavigationSub.DeleteButton.ControlMode = SPControlMode.Edit;
            Buttons.SaveButton.ControlMode = SPControlMode.Edit;
            Buttons.CancelButton.ControlMode = SPControlMode.Edit;
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            CustomFields.EntityType = typeof ( Discussion );
            CustomFields.Title = "Additional Information";

            SPContext context = CustomModel.GetCustomFieldsContext ( typeof ( Discussion ), ItemId, Context, SiteCollectionId, ServerRelativeUrl );
            context.FormContext.FormMode = SPControlMode.Edit;

            Buttons.SaveButton.ItemId = ItemId;
            Buttons.SaveButton.ItemContext = context;
            Buttons.SaveButton.RenderContext = context;

            Buttons.CancelButton.ItemContext = context;
            Buttons.CancelButton.RenderContext = context;
            Buttons.CancelButton.RedirectUrl = Cancel ( );

            NavigationSub.DeleteButton.ItemContext = context;
            NavigationSub.DeleteButton.RenderContext = context;

            litTitle.Text = "Edit Discussion";

            if ( KiiroMaster.V2Header.Project != null && !string.IsNullOrEmpty ( KiiroMaster.V2Header.Project.Title ) )
            {
                litTitle.Text = KiiroMaster.V2Header.Project.Title + " - Edit Discussion";
            }

            Discussion = DiscussionModel.GetById ( ItemId, SiteCollectionId, ServerRelativeUrl );

            if ( Discussion != null )
            {
                PermissionsModel.GetGlobalPermissionBitsForCurrentUser ( Discussion, CurrentUser, SiteCollectionId, ServerRelativeUrl );

                if ( Discussion.PermissionBitsDiscussions != null && Discussion.PermissionBitsDiscussions.Count > 0 && Discussion.PermissionBitsDiscussions [ 2 ] )
                {
                    AddCommandButtons ( );

                    if (!Page.IsPostBack)
                    {
                        PopulateDiscussion();
                    }
                    else // to repopulate the attachments attached with Discussion before editing
                    {
                        if ( Discussion.AttachmentList != null)
                            Attachments.SetAttachments(Discussion.AttachmentList);
                    }
                }
                else
                {
                    Response.Redirect ( Cancel ( ) );
                }
            }
            else
            {
                Response.Redirect ( Cancel ( ) );
            }
        }



        #endregion

        #region Methods
        internal override string Cancel ( )
        {
            string url = string.Format("{0}{1}", ServerRelativeUrl, Constants.ProjectFileUrls.DiscussionsAll);

            if ( Discussion != null && Discussion.IsValid ( ) && Discussion.EditType != EditType.Deleted )
            {
                url = string.Format ( "{0}{1}?id={2}", ServerRelativeUrl, Constants.ProjectFileUrls.DiscussionDisplay, Discussion.Id );
            }

            return url;
        }

        internal override bool Save ( )
        {
            if ( Discussion.PermissionBitsDiscussions [ 2 ] )
            {
                Discussion.ModifiedBy = CurrentUser;
                Discussion.ModifiedDate = DateTime.Now;
                Discussion.Title = txtDiscussionTitle.Text;
                Discussion.Text = WMDTextEditor.Markdown;
                Discussion.HTMLText = WMDTextEditor.Html;
                Discussion.AttachmentList = Attachments.GetAttachments ( );
                Discussion.CustomFieldNamesAndValues = CustomFields.HarvestCustomFieldValues ( );

                Discussion.EditType = EditType.Updated;

                Discussion.AttachmentList = Attachments.ValidateFileExtension(Discussion.AttachmentList);

                Discussion = DiscussionModel.Save ( Discussion, SiteCollectionId, ServerRelativeUrl );

                if (Discussion.IsValid() )
                    Response.Redirect ( Cancel ( ) );
                else
                    PopulateErrorMessages();
            }
            else
            {
                Response.Redirect ( Cancel ( ) );
            }
            return true;
        }

        internal override void Delete ( )
        {
            Discussion.EditType = EditType.Deleted;
            Discussion.ModifiedBy = CurrentUser;
            DiscussionModel.Save ( Discussion, SiteCollectionId, ServerRelativeUrl );
            Response.Redirect ( Cancel ( ) );
        }

        private void PopulateDiscussion ( )
        {
            PopulateActionBar ( );
            WMDTextEditor.DisplayMode = SPControlMode.Edit;
            WMDTextEditor.Markdown = Discussion.Text;
            txtDiscussionTitle.Text = Discussion.Title;

            Attachments.SetAttachments ( Discussion.AttachmentList );
        }

        private void AddCommandButtons ( )
        {
            if ( PermissionBitsDiscussions [ 3 ] )
            {
                LinkButton btnDelete = new LinkButton ( );
                btnDelete.Text = "Delete this Discussion";
                btnDelete.Attributes.Add ( "class", "icon-delete" );
                string js = "javascript:{0}__doPostBack('ctl00$MainContent$V2NavigationSub$diidIODeleteItem','')";
                btnDelete.OnClientClick = string.Format ( js, "if (confirm('Are you sure that you want to delete this discussion?'))" );
                NavigationSub.Commands.Add ( btnDelete );
            }
        }

        private void PopulateActionBar ( )
        {
            if ( Request.UrlReferrer != null && Request.UrlReferrer.OriginalString != null &&
                     ( Request.UrlReferrer.OriginalString.Contains ( Constants.ProjectFileUrls.DiscussionsAll )
                     || Request.UrlReferrer.OriginalString.Contains ( Constants.ProjectFileUrls.DiscussionDisplay ) )
                     )
            {
                lnkBack.NavigateUrl = Request.UrlReferrer.OriginalString;
                pnlActionBar.Visible = true;
            }
        }

        private void PopulateErrorMessages ( )
        {
            lblDiscussionTextMessage.Text = FormattingHelpers.GetErrorMessageText ( Discussion.TextMessage );
            lblDiscussionTitleMessage.Text = FormattingHelpers.GetErrorMessageText(Discussion.TitleMessage);
            Attachments.ValidationMessage = FormattingHelpers.GetErrorMessageText(Discussion.AttachmentListMessage);

        }
        #endregion
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.ProjectPages/Discussions/EditDiscussions.aspx.cs $
 * 
 * 14    2/08/10 2:28p Camerons
 * 
 * 13    1/13/10 6:15p Camerons
 * 
 * 12    1/11/10 11:51a Camerons
 * 
 * 11    1/06/10 12:39p Camerons
 * 
 * 10    12/14/09 2:10p Shafia
 * attachments file extensions validation for discussions, tasks, and
 * issues
 * 
 * 9     26/11/09 2:23p Shafia
 * 
 * 8     24/11/09 10:55a Shafia
 * Discussion now stores the HTML format of the discussion text and uses
 * the WMD editor
 * 
 * 7     17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/